import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/userStore.js';

const routes = [
  {
    path: "/",
    name: "Index",
    title: "首页",
    component: () => import("../views/index.vue"),
  },
  {
    path: "/mall",
    name: "Mall",
    title: "商场",
    component: () => import("../views/mall/index.vue"),
  },
  {
    path: "/login",
    name: "Login",
    title: "登录",
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/register",
    name: "Register",
    title: "注册",
    component: () => import("../views/Register.vue"),
  },
  {
    path: "/user",
    name: "User",
    title: "用户",
    component: () => import("@/views/user/index.vue"),
    meta: { requiresAuth: true } // 添加元信息标识需要认证
  },
  {
    path: "/mitt",
    name: "Mitt",
    title: "Mitt",
    component: () => import("../components/Mitt.vue"),
  },
  {
    path:"/user/List",
    name:"UserList",
    title:"用户列表",
    component:()=> import("@/views/user/List.vue")
  },
  {
    path:"/user/:id",
    name:"UserDetail",
    title:"用户详情",
    component:()=> import("@/views/user/Detail.vue")
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore(); // 在守卫中正确获取 store 实例
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (userStore.isLoggedIn) { // 修正状态名称为 isLoggedIn
      next(); // 已登录，允许访问
    } else {
      next({ path: "/login" }); // 未登录，重定向到登录页
    }
  } else {
    next(); // 不需要认证，直接通过
  }
});

export default router;